<template>
    <div class="app-container">

        <div class="filter-container">

            <el-select v-model="listQuery.filter['house.region_id']" clearable placeholder="请选择区域">
                <el-option
                        v-for="item in formSelections.region"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                </el-option>
            </el-select>

            <el-select v-model="listQuery.filter['house.status']" clearable placeholder="请选择状态">
                <el-option
                        v-for="item in formSelections.statusList"
                        :key="item.id"
                        :label="item.title"
                        :value="item.id">
                </el-option>
            </el-select>

            <el-input v-model="listQuery.filter['house.house_no']" placeholder="请输入房屋编号" style="width: 200px;"
                      col="6"></el-input>
            <el-input v-model="listQuery.filter['house.title']" placeholder="请输入标题" style="width: 200px;"
                      col="6"></el-input>
            <el-button type="primary" @click="searchData">查询</el-button>
            <el-button type="primary" @click="openDialog(null)">新增</el-button>
        </div>

        <el-table :data="list" border style="width: 100%" v-loading="listLoading" fit highlight-current-row>
            <el-table-column fixed prop="id" label="id" width="100"></el-table-column>
            <el-table-column prop="house_no" label=" 房屋编号" min-width="120"></el-table-column>
            <el-table-column prop="photoList" label=" 图片" min-width="120">
                <template slot-scope="scope">
                    <el-image v-if="scope.row.photoList"
                              :key="scope.row.id"
                              style="width: 100px; height: 75px"
                              :src="scope.row.photoList[0].url"
                              :preview-src-list="getPhotos(scope.row.photoList)">
                    </el-image>
                    <span v-else>无</span>
                </template>
            </el-table-column>
            <el-table-column prop="title" label=" 标题" min-width="120"></el-table-column>
            <el-table-column prop="region.title" label=" 所属区域" min-width="120"></el-table-column>
            <el-table-column prop="area" label=" 面积" min-width="120"></el-table-column>
            <el-table-column prop="amount" label=" 租金" min-width="120"></el-table-column>
            <el-table-column prop="create_time" label=" 时间" min-width="120"></el-table-column>
            <el-table-column prop="status" label=" 状态" min-width="120">
                <template slot-scope="scope">
                    {{ statusFormat(scope.row.status)}}
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button type="text" size="small" @click="openDialog(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="destroy(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination :total="total" :page="page" :limit="listQuery.limit" :pageSizes="pageSizes"
                    @pagination="pageChange"></pagination>

        <el-dialog :title="dialogTitle" :visible.sync="formDialogIsVisible" @close="dialogClose">

            <el-form :model="formData" label-width="80px">

                <el-tabs v-model="activeTab" @tab-click="tabClick">
                    <el-tab-pane label="基本信息" name="first">

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="标题">
                                    <el-input v-model="formData.title" autocomplete="off"
                                              placeholder="请输入标题"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="房屋编号">
                                    <el-input v-model="formData.house_no" autocomplete="off"
                                              placeholder="请输入房屋编号"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="价格">
                                    <el-input-number :precision="2" :step="0.01" :min="0" v-model="formData.amount"
                                                     autocomplete="off"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="折扣价">
                                    <el-input-number :precision="2" :step="0.01" :min="0"
                                                     v-model="formData.discount_rate"
                                                     autocomplete="off"></el-input-number>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="面积">
                                    <el-input-number :precision="2" :step="0.01" :min="0" v-model="formData.area"
                                                     autocomplete="off"></el-input-number>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="楼层">
                                    <el-input v-model="formData.floor" autocomplete="off"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="朝向">
                                    <el-select v-model="formData.orientation_id" filterable placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.orientation"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="户型">
                                    <el-select v-model="formData.layout_id" filterable placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.layout"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="轻轨线">
                                    <el-select v-model="formData.subway_line_id" filterable multiple placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.subwayLine"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="配套设置">
                                    <el-select v-model="formData.infrastructure_id" filterable multiple
                                               placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.infrastructure"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="标签">
                                    <el-select v-model="formData.tags" multiple filterable placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.tag"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="租赁方式">
                                    <el-select v-model="formData.type_id" multiple filterable placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.houseType"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="状态">
                                    <el-select v-model="formData.status" placeholder="请选择">
                                        <el-option
                                                v-for="item in formSelections.statusList"
                                                :key="item.id"
                                                :label="item.title"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>

                            <el-col :span="12">
                                <el-form-item label="设备id">
                                    <el-input v-model="formData.uuid" autocomplete="off"
                                              placeholder="请输入设备id"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="排序号">
                                    <el-date-picker
                                            v-model="formData.create_time"
                                            format="yyyy-MM-dd HH:mm:ss"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            type="datetime"
                                            placeholder="选择日期时间">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>

                            <el-row v-if="formData.allow_online_sign === 1">
                                <el-col :span="12">
                                    <el-form-item label="物管费">
                                        <el-input v-model="formData.property_costs" autocomplete="off"
                                                  placeholder="请输入物管费"></el-input>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item label="押金">
                                        <el-input v-model="formData.deposit" autocomplete="off"
                                                  placeholder="请输入物管费"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>

                            <el-form-item label="描述">
                                <el-input type="textarea" v-model="formData.desc" autocomplete="off"
                                          placeholder="请输入描述内容"></el-input>
                            </el-form-item>
                        </el-row>

                    </el-tab-pane>

                    <el-tab-pane label="图片设置" name="second">

                        <el-form-item label="图片">
                            <el-upload ref="uploadComponent"
                                       v-model="formData.photoList"
                                       :multiple="true"
                                       class="photos-uploader"
                                       :action="uploadUrl"
                                       list-type="picture-card"
                                       :file-list="formData.photoList"
                                       :on-remove="photoRemove"
                                       :http-request="uploadImage"
                                       :before-upload="beforeUpload">
                                <div tabindex="0" class="el-upload el-upload--picture-card">
                                    <i data-v-ce9a190e="" class="el-icon-plus photos-uploader-icon"></i>
                                    <input type="file" name="file" class="el-upload__input"></div>
                            </el-upload>
                        </el-form-item>

                    </el-tab-pane>

                    <el-tab-pane label="位置设置" name="third">
                        <el-form-item label="所在地区">
                            <el-col :span="6">
                                <el-select v-model="formData.region_id" placeholder="请选择">
                                    <el-option
                                            v-for="item in formSelections.region"
                                            :key="item.id"
                                            :label="item.title"
                                            :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-col>
                            <el-col :span="16">
                                <el-input v-model="formData.address_text" autocomplete="off"
                                          placeholder="请输入详细地址">
                                    <el-button slot="append" @click="searchLocation">查找</el-button>
                                </el-input>
                            </el-col>
                        </el-form-item>
                        <el-form-item label="位置">
                            <div class="map_container">
                                <baidu-map :center="center" :zoom="zoom" @ready="handler"
                                           style="position: absolute;left: 0;right: 0;top: 0;bottom: 0;"
                                           @click="clickMap"
                                           :scroll-wheel-zoom='true' key="map">
                                    <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
                                    <bm-local-search :keyword="searchMapKey" :auto-viewport="true" location="重庆"
                                                     :pageCapacity="pageCapacity"
                                                     @searchcomplete="searchMapComplete"></bm-local-search>
                                </baidu-map>
                            </div>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="formDialogIsVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
    import {fetchList, add, update, destroy, getStatusList} from '@/api/house'
    import {upload} from '@/api/upload'
    import * as houseType from '@/api/houseType'
    import * as layout from '@/api/layout'
    import * as infrastructure from '@/api/infrastructure'
    import * as orientation from '@/api/orientation'
    import * as region from '@/api/region'
    import * as tag from '@/api/tag'
    import * as subwayLine from '@/api/subwayLine'
    import Pagination from '@/components/Pagination'

    export default {
        name: 'house',
        components: {Pagination},
        data() {
            return {
                //  tab切换标志
                activeTab: "first",
                //  上传地址
                uploadUrl: process.env.VUE_APP_BASE_API + "/Upload/upload",
                //  百度地图标记
                marker: null,
                //  百度地图
                map: null,
                //  地图缩放大小
                zoom: 15,
                //  是否初始化地图
                initMapFlag: false,
                //  地图中心点位置
                center: {
                    lng: 0, lat: 0
                },
                searchMapKey: undefined,
                pageCapacity: 1,
                list: null,
                total: 0,
                page: 1,
                pageSizes: [
                    10, 20, 30
                ],
                listLoading: true,
                listQuery: {
                    offset: 0,
                    limit: 10,
                    sort: "create_time",
                    filter: {
                        "house.title": null,
                        "house.house_no": null,
                        "house.region_id": undefined,
                        "house.status": undefined,
                    },
                    options: {
                        "house.title": "like",
                        "house.house_no": "like",
                    }
                },
                formDialogIsVisible: false,
                formMode: "add",
                formData: {
                    id: undefined,
                    title: undefined,
                    house_no: undefined,
                    uuid: undefined,
                    photoList: [],
                    photos: [],
                    type_id: [],
                    layout_id: undefined,
                    amount: 0.00,
                    discount_rate: 1,
                    region_id: 1,
                    area: 0,
                    status: undefined,
                    floor: 1,
                    address_text: undefined,
                    tags: [],
                    infrastructure_id: [],
                    longitude: undefined,
                    latitude: undefined,
                    orientation_id: undefined,
                    subway_line_id: [],
                    allow_online_sign: 0,
                    desc: undefined,
                    create_time: undefined,
                    property_costs: 0,
                    deposit: 0
                },
                formSelections: {
                    tag: [],
                    houseType: [],
                    layout: [],
                    infrastructure: [],
                    orientation: [],
                    region: [],
                    subwayLine: [],
                    statusList: []
                },
            }
        },
        computed: {
            dialogTitle() {
                return this.formMode === "add" ? "新增" : "编辑"
            },
        },
        created() {
            this.getList();
            this.resetMap();
            this._initData();
        },
        methods: {
            dialogClose() {
                this.searchMapKey = "";
            },
            searchMapComplete(results) {
                if (results === undefined) return false;
                if (results['Ar'].length > 0) {
                    this.setPoint(results['Ar'][0].point, true);
                }
            },
            searchLocation() {
                let title = "重庆";
                this.formSelections.region.forEach(item => {
                    if (item.id === this.formData.region_id) title = item.title;
                });
                this.searchMapKey = title + this.formData.address_text;
            },
            statusFormat(status) {
                let text = "未知";
                this.formSelections.statusList.forEach(item => {
                    if (parseInt(item.id) === status) text = item.title;
                });
                return text;
            },
            getPhotos(photos) {
                return photos.map(item => {
                    return item.url;
                });
            },
            async _initData() {
                let searchQuery = {
                    infinite: true,
                };
                let houseTypeList = await houseType.fetchList(searchQuery);
                let layoutList = await layout.fetchList(searchQuery);
                let infrastructureList = await infrastructure.fetchList(searchQuery);
                let orientationList = await orientation.fetchList(searchQuery);
                let regionList = await region.fetchList(searchQuery);
                let tagList = await tag.fetchList(searchQuery);
                let subwayLineList = await subwayLine.fetchList(searchQuery);
                let statusList = await getStatusList();
                this.formSelections.statusList = statusList.data;
                this.formSelections.layout = layoutList.data.list;
                this.formSelections.houseType = houseTypeList.data.list;
                this.formSelections.infrastructure = infrastructureList.data.list;
                this.formSelections.orientation = orientationList.data.list;
                this.formSelections.region = regionList.data.list;
                this.formSelections.tag = tagList.data.list;
                this.formSelections.subwayLine = subwayLineList.data.list;
            },
            //  重置地图
            resetMap() {
                this.center.lng = 106.584712;
                this.center.lat = 29.563066;
                this.zoom = 15;
                this.setPoint(this.center, true);
            },
            //  初始化地图回调
            handler({BMap, map}) {
                let point = new BMap.Point(this.center.lng, this.center.lat);
                this.marker = new BMap.Marker(point);
                this.map = map;
                this.map.centerAndZoom(point, this.zoom);
                this.map.addOverlay(this.marker);
                this.initMapFlag = true;
            },
            //  地图点击事件
            clickMap(e) {
                this.setPoint({
                    lng: e.point.lng,
                    lat: e.point.lat
                }, false);
            },
            //  设置地图中锚点位置
            setPoint(position, isZoom) {
                if (!this.initMapFlag) return;
                let point = new BMap.Point(position.lng, position.lat);
                this.marker.setPosition(point);
                this.formData.latitude = position.lat;
                this.formData.longitude = position.lng;
                if (isZoom) {
                    setTimeout(() => {
                        this.map.centerAndZoom(point, this.zoom);
                    }, 100);
                }
            },
            //  删除图片
            photoRemove(file) {
                this.formData.photoList = this.formData.photoList.filter((data) => {
                    if (data.id === file.id) return false;
                    return true;
                });
            },
            uploadImage(file) {
                let formData = new FormData();
                formData.append("file", file.file);
                upload(formData).then(response => {
                    if (response.code === 200) {
                        this.formData.photoList.push({
                            id: response.data.fileId,
                            url: response.data.filePath,
                        });
                    } else {
                        this.formData.photoList = Object.assign([], this.formData.photoList);
                    }

                });
            },
            //  图片上传之前回调
            beforeUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 5;
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 5MB!');
                }
            },
            //  选项卡切换时,地图重新定位
            tabClick(tab, event) {
                if (tab.name === "third") {
                    let position = {};
                    if (this.formMode === "add") {
                        position = {
                            lat: this.center.lat,
                            lng: this.center.lng
                        };
                    } else {
                        position = {
                            lat: this.formData.latitude,
                            lng: this.formData.longitude
                        };
                    }
                    this.setPoint(position, true);
                }
            },
            pageChange(data) {
                this.page = data.page;
                this.listQuery.limit = data.limit;
                this.listQuery.offset = (this.page - 1) * this.listQuery.limit;
                this.refresh(false);
            },
            openDialog(row) {
                this.activeTab = "first";
                this.formDialogIsVisible = true;
                if (!!row) {
                    this.formMode = "edit";
                    this.formData = {
                        id: row.id,
                        title: row.title,
                        house_no: row.house_no,
                        uuid: row.uuid,
                        type_id: row.type_id,
                        layout_id: row.layout_id,
                        amount: row.amount,
                        photoList: Object.assign([], row.photoList),
                        discount_rate: row.discount_rate,
                        region_id: row.region_id,
                        area: row.area,
                        status: row.status,
                        floor: row.floor,
                        address_text: row.address_text,
                        tags: row.tags,
                        infrastructure_id: row.infrastructure_id,
                        longitude: row.longitude,
                        latitude: row.latitude,
                        orientation_id: row.orientation_id,
                        subway_line_id: row.subway_line_id,
                        allow_online_sign: row.allow_online_sign,
                        desc: row.desc,
                        create_time: row.create_time,
                        version: row.version,
                        property_costs: row.property_costs,
                        deposit: row.deposit
                    };
                    this.zoom = 18;
                    this.setPoint({
                        lat: row.latitude,
                        lng: row.longitude
                    }, true);
                } else {
                    this.formMode = "add";
                    this.formData = {
                        id: undefined,
                        title: undefined,
                        house_no: undefined,
                        uuid: undefined,
                        photoList: [],
                        photos: [],
                        status: undefined,
                        type_id: [],
                        layout_id: undefined,
                        amount: 0.00,
                        discount_rate: 1,
                        region_id: 1,
                        area: 0,
                        floor: 1,
                        address_text: undefined,
                        tags: [],
                        infrastructure_id: [],
                        longitude: undefined,
                        latitude: undefined,
                        orientation_id: undefined,
                        allow_online_sign: 0,
                        subway_line_id: [],
                        desc: undefined,
                        create_time: undefined,
                        property_costs: 0,
                        version: 0,
                        deposit: 0
                    };
                    this.resetMap();
                }
            },
            save() {
                let promise;
                this.listLoading = true;
                let formData = this.formData;
                formData.photos = formData.photoList.map(function (value) {
                    return value.id;
                });
                if (this.formMode === "add") {
                    promise = add(this.formData);
                } else {
                    promise = update(this.formData);
                }
                promise.then(() => {
                    this.refresh();
                }).catch(() => {
                    this.listLoading = false;
                });
            },
            destroy(id) {
                this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async() => {
                    this.listLoading = true;
                    await destroy({id});
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch((error) => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                }).finally(() => {
                    this.refresh();
                });
            },
            searchData() {
                this.refresh(true);
            },
            refresh(isAll = false) {
                this.resetMap();
                this.formDialogIsVisible = false;
                this.listLoading = false;
                if (isAll) {
                    this.page = 1;
                }
                this.getList();
            },
            getList() {
                this.listLoading = true
                fetchList(this.listQuery).then(response => {
                    let {data} = response;
                    this.list = data.list
                    this.total = response.data.count
                    this.listLoading = false
                }).catch(() => {
                    this.listLoading = false
                });
            },
        },
        watch: {
            page: function (newVluae, oldVluae) {
                this.listQuery.offset = (newVluae - 1) * this.listQuery.limit;
            },
        },
    }
</script>
<style lang="scss">
    .photos-uploader {

    .el-upload-list__item {
        width: 140px;
        height: 105px;
    }

    .el-upload.el-upload--picture-card {
        width: 140px;
        height: 105px;
        line-height: 105px;
    }

    }

    .map_container {
        width: 100%;
        position: relative;
        height: 480px;
        display: table;
    }
</style>
